package cn.cdzdjd.service.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.stereotype.Service;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.DuanYouService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;

@Service
public class DuanYouServiceImpl implements DuanYouService {
	private final String baseUrl = "http://dyclubs123.tpddns.cn:85/appapi/?dynamicid={dynamicid}&service=Dynamic.GetDynamic";

	@Override
	public VideoInfoVO getVideoInfo(String url) {

		try {
			Map<String, String> map = UrlUtil.convertUrlParamsToMap(new URL(url));
			if (map.get("dynamicid") == null) {
				throw new RenException("无效的链接");
			}
			HttpResponse<String> response = Unirest.get(baseUrl.replace("{dynamicid}", map.get("dynamicid")))
					.asString();
			String jsonStr = response.getBody();
			JSONObject json = new JSONObject(jsonStr);
			if (json.getInt("ret") == 200) {
				JSONObject data = json.getJSONObject("data");
				JSONObject videoInfo = data.getJSONArray("info").getJSONObject(0);
				String title = videoInfo.getString("title");
				String videoUrl = videoInfo.getString("href");
				String posterUrl = videoInfo.getString("video_thumb");
				List<String> videoList = new ArrayList<>();
				List<String> posterList = new ArrayList<>();
				videoList.add(UrlUtil.setHttps(videoUrl));
				posterList.add(UrlUtil.setHttps(posterUrl));
				return new VideoInfoVO(videoList, posterList, title, null);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		throw new RenException(ErrorCode.PARSE_ERROR);
	}

}
